import { useEffect, useRef, useState } from 'react';
import { Divider, Pagination, Table } from 'antd';
import { columns, dataList01, dataList02 } from './data';
import { Reference } from 'rc-table';
import { AppStyle, TableStyle } from './style';
import { debounce } from 'lodash-es';

type FlexibleProps = {
	dataList: any[];
};
const Flexible = (props: FlexibleProps) => {
	const { dataList } = props;
	const tableRef = useRef<Reference>();
	const pageRef = useRef<HTMLDivElement>();

	const [scrollHeight, setScrollHeight] = useState(0);
	const [showScroll, setShowScroll] = useState(false);

	const showScrollFn = () => {
		const totalHeight = window.innerHeight;
		const tableThead = tableRef.current.nativeElement.getElementsByClassName('ant-table-thead')[0];
		const topDistance = tableThead.getBoundingClientRect().bottom;
		const pageTop = pageRef.current.getBoundingClientRect().top;
		const result = totalHeight - topDistance - (totalHeight - pageTop);
		const tableTbody = tableRef.current.nativeElement.getElementsByClassName('ant-table-tbody')[0];
		if (result < tableTbody.clientHeight) {
			setScrollHeight(result);
			setShowScroll(true);
		} else {
			setScrollHeight(0);
			setShowScroll(false);
		}
	};

	const handleShowScroll = debounce(showScrollFn, 200);

	useEffect(() => {
		if (tableRef.current) {
			showScrollFn();
		}
		window.addEventListener('resize', handleShowScroll);
		return () => window.removeEventListener('resize', handleShowScroll);
	}, []);

	return (
		<TableStyle>
			<Table
				ref={tableRef}
				size="small"
				rowKey="id"
				dataSource={dataList}
				columns={columns}
				pagination={false}
				scroll={showScroll ? { y: scrollHeight, x: 'max-content' } : { x: 'max-content' }}
			/>
			<div className="pagination" ref={pageRef}>
				<Pagination
					showTitle
					total={5}
					current={1}
					pageSize={10}
					onChange={(pageNo) => console.log(pageNo)}
				/>
			</div>
		</TableStyle>
	);
};

const App = () => {
	const [data01, setData01] = useState([]);
	const [data02, setData02] = useState([]);

	useEffect(() => {
		setTimeout(() => setData01(dataList01), 500);
		setTimeout(() => setData02(dataList02), 1000);
	}, []);

	return (
		<AppStyle>
			<Flexible dataList={data01} />
			<Divider />
			<Flexible dataList={data02} />
		</AppStyle>
	);
};

export default App;
